package ofpof.web.validator;

import java.util.regex.Pattern;

import ofpof.domain.User;
import ofpof.domain.dao.UserDao;
import ofpof.web.form.UserForm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class UserFormValidator implements Validator {
	
	public static final Pattern emailPattern = Pattern.compile("\\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b");
	
	@Autowired
	private UserDao userDao;

	@Override
	public boolean supports(Class<?> clazz) {
		return UserForm.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object bean, Errors errors) {
		UserForm userForm = (UserForm) bean;
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"user.password", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"password", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"user.email", "field.required");
		
		if (!userForm.isAcceptedTerms()) {
			errors.rejectValue("acceptedTerms", "user.termsconditions.notaccepted");
		}
		
		if ( ! errors.hasFieldErrors("password") &&  ! errors.hasFieldErrors("user.password")  ) {
			boolean passwordsDontMatch = !userForm.getPassword().equals(userForm.getUser().getPassword());
			if (passwordsDontMatch) {
				errors.rejectValue("user.password", "user.password.notmatch");
			}
		}
		
		if (!errors.hasFieldErrors("user.password")) {
			if (userForm.getUser().getPassword().length() < 5) {
				errors.rejectValue("user.password", "user.password.length.five");
			}
		}
		

		if (!errors.hasFieldErrors("user.email")) {
			boolean isValidEmail = emailPattern.matcher(userForm.getUser().getEmail()).matches();
			if (!isValidEmail) {
				errors.rejectValue("user.email", "user.email.invalid");
			}
		}
		
		if (!errors.hasFieldErrors("user.email")) {
			String email = userForm.getUser().getEmail();
			User user = userDao.findByEmail(email);
			if (user != null) {
				errors.rejectValue("user.email", "user.email.notunique");
			}
		}

		
	}

}
